import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Root',
    // 不设置重定向，通过导航守卫动态处理
    component: () => import('../pages/Login.vue'),
    meta: { dynamicRedirect: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../pages/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../pages/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/feed',
    name: 'Feed',
    component: () => import('../pages/Feed.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../pages/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/publish',
    name: 'Publish',
    component: () => import('../pages/Publish.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/log',
    name: 'log',
    component: () => import('../pages/Log.vue'),
  },
  {
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token

  // 处理根路径的动态重定向
  if (to.matched.some(record => record.meta.dynamicRedirect)) {
    if (isLoggedIn) {
      next({ path: '/feed' })
    } else {
      next({ path: '/login' })
    }
    return
  }

  // 如果访问的是不需要认证的页面，直接通过
  if (to.matched.some(record => record.meta.requiresAuth === false)) {
    // 如果用户已登录且访问登录或注册页面，重定向到首页
    if (isLoggedIn && (to.path === '/login' || to.path === '/register')) {
      next({ path: '/feed' })
    } else {
      next()
    }
    return
  }

  // 对于需要认证的页面，检查是否已登录
  if (!isLoggedIn) {
    // 保存用户想要访问的页面，登录后可以直接跳转过去
    next({
      path: '/login',
      query: { redirect: to.fullPath !== '/' ? to.fullPath : '/feed' }
    })
    return
  }

  // 用户已登录且访问需要认证的页面，直接通过
  next()
})

export default router 